package com.xique.door.controller;


import com.xique.common.core.text.Convert;
import com.xique.common.core.utils.AliossUtil;
import com.xique.common.core.utils.StringUtils;
import com.xique.common.core.utils.poi.ExcelUtil;
import com.xique.common.core.web.controller.BaseController;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.core.web.page.TableDataInfo;
import com.xique.common.log.annotation.Log;
import com.xique.common.log.enums.BusinessType;
import com.xique.common.security.annotation.PreAuthorize;
import com.xique.door.bean.domain.Visitor;
import com.xique.door.bean.request.commandV1.DeviceCommandDownloadRequest;
import com.xique.door.bean.request.commandV1.DeviceCommandUserInfoDelRequest;
import com.xique.door.bean.request.commandV1.DeviceCommandUserInfoDownloadRequest;
import com.xique.door.bean.request.visitor.*;
import com.xique.door.bean.validation.VisitorValidation;
import com.xique.door.biz.service.IDeviceCommandNewService;
import com.xique.door.biz.service.IVisitorBizService;
import com.xique.door.constant.UserConstant;
import com.xique.door.constant.VisitorConstants;
import com.xique.door.service.IVisitorService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 * 访客信息Controller
 *
 * @author caogq
 * @date 2021-06-12
 */
@RestController
@RequestMapping("visitor")
public class VisitorController extends BaseController {

    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private VisitorValidation visitorValidation;

    @Autowired
    private IDeviceCommandNewService deviceCommandNewService;

    @Autowired
    private IVisitorBizService visitorBizService;

    @Autowired
    private AliossUtil aliossUtil;

    /**
     * 查询访客信息列表
     */
    @PreAuthorize(hasPermi = "oms:doorVisitor:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Visitor visitor) {
        startPage();
        List<Visitor> list = visitorService.selectVisitorList(visitor);
        return getDataTable(list);
    }

    /**
     * 导出访客信息列表
     */
    @PreAuthorize(hasPermi = "oms:doorVisitor:export")
    @PostMapping("/export")
    @ResponseBody
    public void export(HttpServletResponse response,Visitor visitor) throws IOException {
        List<Visitor> list = visitorService.selectVisitorList(visitor);
        ExcelUtil<Visitor> util = new ExcelUtil<Visitor>(Visitor.class);
         util.exportExcel(response,list, "visitor");
    }

    /**
     * 新增保存访客信息
     */
    @PreAuthorize(hasPermi = "oms:doorVisitor:add")
    @Log(title = "访客信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Visitor visitor) {
        Boolean validation = visitorValidation.saveVisitor(visitor);
        if (!validation) {
            return AjaxResult.error("表单填写有误，请检查后重新提交");
        }
        //1、新增访客表信息
        int i = visitorService.insertVisitor(visitor);
        if (i < 0) {
            return AjaxResult.error("访客保存失败");
        }
        //2、访客上传照片，下发设备
        if (StringUtils.isNotEmpty(visitor.getFaceUrl())) {
            Visitor newVisitor = visitorService.selectVisitorById(visitor.getId());
            DeviceCommandDownloadRequest request = new DeviceCommandDownloadRequest();
            request.setUserId(newVisitor.getUserId());
            request.setVisitor(newVisitor);
            request.setParkId(newVisitor.getParkId());
            DeviceCommandUserInfoDownloadRequest visitorRequest = new DeviceCommandUserInfoDownloadRequest();
            visitorRequest.setUserId(visitor.getId());
            visitorRequest.setFromType("admin");
            visitorRequest.setAsync(false);
            visitorRequest.setUserType(UserConstant.Type.VISITOR);
            return deviceCommandNewService.userInfoDownload(visitorRequest);
        }

        return AjaxResult.success("访客保存成功!");
    }

    /**
     * 修改保存访客信息
     */
    @PreAuthorize(hasPermi = "oms:doorVisitor:edit")
    @Log(title = "访客信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Visitor visitor) {

        Boolean validation = visitorValidation.saveVisitor(visitor);
        if (!validation) {
            return AjaxResult.error("表单填写有误，请检查后重新提交");
        }
        //是否下发
        Boolean flag = false;
        if (StringUtils.isNotEmpty(visitor.getFaceUrlNew()) && !visitor.getFaceUrlNew().equals(visitor.getFaceUrl())) {
            visitor.setFaceUrl(visitor.getFaceUrlNew());
            flag = true;
        }

        int i = visitorService.updateVisitor(visitor);
        if (i < 0) {
            return AjaxResult.error("访客修改失败");
        }
        //2、访客照片有更新，下发设备
        if (flag) {
            Visitor newVisitor = visitorService.selectVisitorById(visitor.getId());
            DeviceCommandDownloadRequest request = new DeviceCommandDownloadRequest();
            request.setUserId(newVisitor.getUserId());
            request.setVisitor(newVisitor);
            request.setParkId(newVisitor.getParkId());
            DeviceCommandUserInfoDownloadRequest visitorRequest = new DeviceCommandUserInfoDownloadRequest();
            visitorRequest.setUserId(visitor.getId());
            visitorRequest.setFromType("admin");
            visitorRequest.setAsync(false);
            visitorRequest.setUserType(UserConstant.Type.VISITOR);
            return deviceCommandNewService.userInfoDownload(visitorRequest);
        }
        return AjaxResult.success("访客修改成功!");
    }

    /**
     * 删除访客信息
     */
    @PreAuthorize(hasPermi = "oms:doorVisitor:remove")
    @Log(title = "访客信息", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        String[] idArrar = Convert.toStrArray(ids);
        //判断是否存在权限组，存在给对应设备发删除请求
        for (int i = 0; i < idArrar.length; i++) {
            Visitor visitor = visitorService.selectVisitorById(Long.valueOf(idArrar[i]));
            DeviceCommandUserInfoDelRequest delRequest = new DeviceCommandUserInfoDelRequest();
            delRequest.setGroupId(null);
            delRequest.setUserId(visitor.getId());
            delRequest.setAsync(true);
            delRequest.setUserType(UserConstant.Type.VISITOR);
            AjaxResult delResult = deviceCommandNewService.permissionUserInfoDel(delRequest);
        }
        AjaxResult result = visitorService.deleteVisitorByIds(ids);
        return AjaxResult.success("删除成功");
    }

    @PreAuthorize(hasPermi = "door:visitor:list")
    @GetMapping("/v2/list")
    public AjaxResult listV2(VisitorListRequest request) {
        startPage();
        return visitorBizService.getVisitorList(request);
    }

    @PreAuthorize(hasPermi = "door:visitor:add")
    @PostMapping("/v2/add")
    public AjaxResult addV2(@RequestBody @Valid VisitorAddRequest request) {
        request.setVerifyType(VisitorConstants.VerifyType.ESTATE);
        return visitorBizService.addVisitor(request);
    }

    @PreAuthorize(hasPermi = "door:visitor:edit")
    @GetMapping("/v2/detail")
    public AjaxResult detailV2(Long id) {
        return visitorBizService.visitorDetail(id);
    }

    @PreAuthorize(hasPermi = "door:visitor:edit")
    @PostMapping("/v2/edit")
    public AjaxResult editV2(@RequestBody VisitorEditRequest request) {
        return visitorBizService.editVisitor(request);
    }

    @PreAuthorize(hasPermi = "door:visitor:remove")
    @DeleteMapping("/v2/remove")
    public AjaxResult removeV2(Long id) {
        return visitorBizService.removeVisitor(id);
    }

    @PreAuthorize(hasPermi = "door:visitor:edit")
    @PostMapping("/v2/changeStatus")
    public AjaxResult changeStatusV2(@RequestBody VisitorEditRequest request) {
        return visitorBizService.changeVisitorStatus(request);
    }

    @PreAuthorize(hasPermi = "door:visitor:edit")
    @PostMapping("/v2/verify")
    public AjaxResult verifyV2(@RequestBody VisitorVerifyRequest request) {
        return visitorBizService.verifyVisitor(request);
    }

    @PreAuthorize(hasPermi = "door:visitor:list")
    @GetMapping("/v2/authorizeList")
    public AjaxResult authorizeList(VisitorAuthorizeListRequest request) {
        return visitorBizService.visitorAuthorizeList(request);
    }

    @PreAuthorize(hasPermi = "door:visitor:edit")
    @PostMapping("/v2/syncVisitor")
    public AjaxResult syncVisitor(@RequestBody VisitorSyncRequest request) {
        return visitorBizService.syncVisitor(request);
    }

    @ApiOperation(value = "删除访客人脸图片")
    @DeleteMapping("/deleteFacePic")
    public AjaxResult deleteFacePic(@RequestParam(value = "id",required = false) Long visitorId, @RequestParam("faceKey") String faceKey) {
        if (StringUtils.isEmpty(faceKey)) {
            return AjaxResult.error("必填项不能为空");
        }
        //1、删除oss上的存储
        String status = aliossUtil.delete(faceKey);

        if (status.equals("error")) {
            return AjaxResult.error("error", "oss删除失败！！！");
        }
        if (StringUtils.isNotNull(visitorId)) {
            //2、清除图片和用户的关联
            try {
                visitorService.clearVisitorUrl(visitorId);
            } catch (Exception e) {
                return AjaxResult.error("error", "图片和用户关系删除失败！！！");
            }
        }

        return AjaxResult.success();
    }
}
